import axios from 'axios';
import router from '../router';
import store from '../vuex/store';
import { Message } from 'element-ui'
import QS from "qs"
let baseUrl = ''
switch (IS_DEV) {
	// 正式环境
    case 'PRO':
        baseUrl = ''
        break
	//正常环境
    case 'DEV':
		baseUrl = '/'
        baseUrl = 'http://kc489b65.natappfree.cc'
        break
		// 测试环境
    case 'TEST':
        baseUrl = ''
        break
    default:
        break
}
axios.defaults.baseURL = baseUrl;
// 请求超时时间
axios.defaults.timeout = 500000;
axios.defaults.withCredentials = true;

// 设置默认请求头
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest',
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
	  'Content-Type': 'application/json',
    //'Content-Type': 'multipart/form-data'
}
// 序列化参数
/*axios.defaults.transformRequest = (data) => {
    data = QS.stringify(data);
    return data;
  }*/
const toLogin = () => {
    router.replace({
        path: '/login',
    });
}
// 请求拦截器
axios.interceptors.request.use(
    config => {
        let token = sessionStorage.getItem('token');
        if(token){
            config.headers.Authorization = token
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    })
// 响应拦截器
axios.interceptors.response.use(
	response => {
    if(response.data.code==5001){
    	Message.warning({
    	   message: '登录已过期或登录信息不存在，请重新登录!'
    	})
    	localStorage.removeItem("token");
    	setTimeout(() => {
    	    toLogin();
    	}, 1500);
    	return
    }
		if (response.status === 200) {
		  if((response.data).hasOwnProperty('reason')){
		    let _tk = response.data.reason;
		    if(_tk.indexOf('session')!=-1){
		      Message.warning({
		         message: '当前session已过期，请重新登录!'
		      })
		      localStorage.removeItem("token");
		      setTimeout(() => {
		          toLogin();
		      }, 1500);
		    }else{
		      return Promise.resolve(response);
		    }
		  }else{
		    return Promise.resolve(response);
		  }
		}
		else {
			return Promise.reject(response);
		}
	},
	error => {
		Message.warning({
			message: '网络请求不存在'
		})
		// if (error.response.status) {
		// 	switch (error.response.status) {
		// 		case 401:
		// 			toLogin();
		// 			break;
		// 		case 403:
		// 			Message.warning({
		// 				message: '登录过期，请重新登录'
		// 			})
		// 			localStorage.removeItem('token');
		// 			store.commit('loginSuccess', null);
		// 			setTimeout(() => {
		// 				toLogin();
		// 			}, 1000);
		// 			break;
		// 		case 404:
		// 			Message.warning({
		// 				message: '网络请求不存在'
		// 			})
		// 			break;
		// 		default:
		// 			Message.warning({
		// 				message: '网络请求出现错误，请稍后再试'
		// 			})
		// 	}
		// 	return Promise.reject(error.response);
		// }
	}
);
// get请求
export function getFun(url, _params){
    return new Promise((resolve, reject) =>{
        axios.get(url, {params:_params})
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err.data)
        })
    });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postFun(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url,params)
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err.data)
        })
    });
}
export function postEncoded(url, params) {
	return new Promise((resolve, reject) => {
		// axios.defaults.transformRequest = (data) => {
		//     data = QS.stringify(data);
		//     return data;
		//   }
		axios.post(url, QS.stringify(params), {
				headers: {
			  'X-Requested-With': 'XMLHttpRequest',
					'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
					//'Content-Type': 'multipart/form-data'
				}
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}
export function postUpload(url, params) {
	return new Promise((resolve, reject) => {
		axios.post(url, params, {
				headers: {
          'X-Requested-With': 'XMLHttpRequest',
					// 'Content-Type':'multipart/form-data;boundary=----WebKitFormBoundaryABC123',
          'Content-Type': 'multipart/form-data'
				}
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}
export { baseUrl }
